#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
PLAIN='\033[0m'

FOLDER='/media/lemon/NODE_F767ZI'

PASSWD="lemon"

function error() {
    echo -e "${RED}[ERROR]: ${PLAIN}$*"
}
function info() {
    echo -e "${GREEN}[INFO]: ${PLAIN}$*"
}
function notice() {
    echo -e "${YELLOW}[NOTICE]: ${PLAIN}$*"
}

function errot_exit(){
    echo -e "${RED}[ERROR]: ${PLAIN}ERROR!"
    exit
}  


FILE=`find -name "*.bin"`

if [ ! $FILE ];then
    FILE=`find -name "*.hex"`
    if [ ! $FILE ];then
        error "not find binary file"
        exit
    fi
fi

info "find binary file: ${YELLOW}${FILE}${PLAIN}"



DEV=`echo $PASSWD | sudo -S fdisk -l | grep -B 1 "microcontroller" | grep "Disk /"| sed 's/Disk \//\//g;s/：.*//g'`
CONT=`df -h $DEV | grep "/dev"| sed 's/ .*\// /g' | wc -l`
DISK=`df -h $DEV | grep "/dev"| sed 's/ .*//g'`
# echo "find $CONT device:"
BOARDPATH=`df -h $DEV | grep "/dev"| sed 's/.* //g'`
BOARDNAME=`echo $BOARDPATH | sed 's/.*\///g'`

#echo $BOARDPATH

if [ ! $DEV ];then
    error "not find device!" 
    exit
fi

if [ -d $BOARDPATH ];then
    info "download..."
    
    info "find device: ${YELLOW}$BOARDNAME${PLAIN}"

    cp ${FILE} ${BOARDPATH} 2>/dev/null || errot_exit

    info "download finished !"

    info 'wait device restart...'
    while [ -d $BOARDPATH ]
    do
        sleep 1
    done
    sleep 3

    if [ -f $BOARDPATH/FAIL.TXT ];then
        error `cat $BOARDPATH/FAIL.TXT`
        exit
    fi
    info "all finished !"
else
    error "not find device!"
fi





